<?php

namespace app\admin\controller;

use app\common\controller\AdminController;

//引入外部函数
use app\common\model\hfztcy\LibMember;
use app\common\model\hfztcy\LibOrder;
use app\common\model\hfztcy\LibStore;
use app\common\model\hfztcy\LibStoresApply;
use app\common\model\LibUser;
use common\Common;
use think\Db;
use think\Exception;


/**
 * 门店列表
 * @name Store.php
 * @package hfztcy
 * @message controller
 * @author rxy
 * @version 1.0
 * @copyright CHANGE INC
 * @since 2020-6-5
 */
class Store extends AdminController
{
    protected $model;

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new LibStore();
        $this->rightVerify(session('admin'), url("admin/Login/login"));
        parent::__construct();
    }

    /**
     * 列表页
     */
    function storeList()
    {
        $this->getSetMenu($this);
        $this->log(__CLASS__, __FUNCTION__, "列表页", 1, 'view');
        return $this->fetch('Store/storeList/storeList');
    }

    /**
     * 添加门店页面
     */
    function addStore()
    {
        $this->getMenu($this);
        $this->log(__CLASS__, __FUNCTION__, "添加门店页面", 1, 'add');
        return $this->fetch('Store/addStore/addStore');
    }

    /**
     * 修改门店页面
     */
    function editStore()
    {
        $this->getMenu($this);
        $id = input('id');
        $model = new LibStore();
        $storeInfo = $model->findStore(['id' => $id]);
        $storeInfo['data']['vcr'] = str_replace('upload/','upload/sliceVideo/',$storeInfo['data']['vcr']);
        $storeInfo['data']['photo_list_str'] = $storeInfo['data']['photo_list'];
        $storeInfo['data']['photo_list'] = explode(',',$storeInfo['data']['photo_list']);
        $this->assign('storeInfo',$storeInfo['data']);
        $this->log(__CLASS__, __FUNCTION__, "修改门店页面", 1, 'add');
        return $this->fetch('Store/editStore/editStore');
    }

    /**
     * Info: 替换用户
     * Date: 2023/2/18 16:11
     */
    function setStoreUser ()
    {
        $store_id = input('store_id');
        $user_id = input('user_id');
        $findStoreRes = $this->model->findStore(['id' => $store_id]);
        if ($findStoreRes['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1, '门店不存在', []));
            die;
        }

        $memberModel = new LibMember();
        $findUserRes = $memberModel->findMember(['user_id' => $user_id]);

        $adminInfo['user_id'] = $user_id;
        $adminInfo['bind_time']  = Common::getTime();
        $this->model->updateStore(['id' => $store_id],$adminInfo);

        echo json_encode(Common::errorArray(0, '替换成功', $findUserRes['data']));
        die;
    }

    /**
     * 添加店铺
     */
    function insertStore()
    {
        $adminInfo = $this->getArgsList($this, array("username", "password", "title", "province", "city", "district", "address","lat","lng","photo_list","vcr", "user_id","mobile","open_time","fwxy","yhhd","uid"));
        $findStoreRes = $this->model->findStore(['username' => $adminInfo['username']]);
        if ($findStoreRes['errorCode'] == 0) {
            echo json_encode(Common::errorArray(1, '账号名称已存在', []));
            die;
        }
        Db::startTrans();
        try {
            if (!$adminInfo['province'] || !$adminInfo['city'] || !$adminInfo['district']) {
                echo json_encode(Common::errorArray(1, '请在地图选择地址', []));
                die;
            }
            // 门店头像
            $result = $this->model->uploadStoreImgs();
            if ($result['errorCode'] == 0) {
                $adminInfo['storeimgs'] = $result['data']['path'];
            } elseif ($result['errorCode'] == 1) {
                echo json_encode(Common::errorArray(1, $result['errorInfo'], []));
                die;
            }
            // 视频封面图
            $result = $this->model->uploadStoreVcrImgs();
            if ($result['errorCode'] == 0) {
                $adminInfo['imgs'] = $result['data']['path'];
            } elseif ($result['errorCode'] == 1) {
                echo json_encode(Common::errorArray(1, $result['errorInfo'], []));
                die;
            }
            $adminInfo['area'] = $adminInfo['district'];
            $adminInfo['password'] = trim($adminInfo['password']);
            unset($adminInfo['district']);
            if ($adminInfo['user_id']) {
                $apply_id = input('apply_id',0);
                if ($apply_id) {
                    (new LibStoresApply())->updateStoreApply(['id' => $apply_id] , ['state' => 1]);
                }
                /*************/
                $memberModel = new LibMember();
                $findRes = $memberModel->findMember(['user_id' => $adminInfo['uid']]);
                if ($findRes['errorCode'] == 0) {
                    // 更新用户身份 身份0游客1普通用户2vip会员3红娘4门店
                    if (strpos($findRes['data']['state'],'3') !== false) { // 如果用户是红娘
                        $identity = explode(',',$findRes['data']['state']);
                        array_push($identity,'4');// 将门店角色加入当前用户
                        $identity = implode(',',$identity);
                    } else {
                        $identity = '4';
                    }
                    $memberModel->updateMember(['user_id' => $adminInfo['uid']] , ['state' => $identity,'oldIdentity' => $findRes['data']['state']]);
                    (new LibUser())->updateUser(['id' => $adminInfo['uid']],['identity' => $identity]);
                }
                /*************/
                $adminInfo['bind_time']  = Common::getTime();
            }
            $adminInfo['add_time'] = Common::getTime();
            $result = $this->model->addStore($adminInfo);
            Db::commit();
            echo json_encode($result);
        } catch (Exception $exception) {
            Db::rollback();
            echo json_encode(Common::errorArray(1,'绑定失败',$exception->getMessage()));
        }
    }

    /**
     * 修改店铺
     */
    function updateStore()
    {
        $adminInfo = $this->getArgsList($this, array("id", "username", "title", "province", "city", "district", "address","lat","lng","photo_list","vcr", "mobile","open_time","fwxy","yhhd"));
        $findStoreRes = $this->model->findStore(['username' => $adminInfo['username']]);
        if ($findStoreRes['errorCode'] == 0 && $findStoreRes['data']['id'] != $adminInfo['id']) {
            echo json_encode(Common::errorArray(1, '账号名称已存在', []));
            die;
        }
        if (!$adminInfo['province'] || !$adminInfo['city'] || !$adminInfo['district']) {
            echo json_encode(Common::errorArray(1, '请在地图选择地址', []));
            die;
        }
        $adminInfo['area'] = $adminInfo['district'];
        unset($adminInfo['district']);
        $model = new LibStore();
        $findStoreRes = $model->findStore(['id' => $adminInfo['id']]);
        if ($findStoreRes['errorCode'] == 0) {
            // 门店头像
            $imgStoreImgs = input('imgStoreImgs', 0);
            if ($imgStoreImgs == '1') {
                $result = $this->model->uploadStoreImgs();
                if ($result['errorCode'] == 0) {
                    $findStoreRes['data']['storeimgs'] && unlink(ROOT_PATH.'public/'.$findStoreRes['data']['storeimgs']);
                    $adminInfo['storeimgs'] = $result['data']['path'];
                } elseif ($result['errorCode'] == 1) {
                    echo json_encode(Common::errorArray(1, $result['errorInfo'], []));
                    die;
                }
            }

            // 视频封面图
            $vcr_flag = input('imgFlagCover', 0);
            if ($vcr_flag == '1') {
                $result = $this->model->uploadStoreVcrImgs();
                if ($result['errorCode'] == 0) {
                    $findStoreRes['data']['imgs'] && unlink(ROOT_PATH.'public/'.$findStoreRes['data']['imgs']);
                    $adminInfo['imgs'] = $result['data']['path'];
                } elseif ($result['errorCode'] == 1) {
                    echo json_encode(Common::errorArray(1, $result['errorInfo'], []));
                    die;
                }
            }
            $result = $this->model->updateStore(['id' => $adminInfo['id']],$adminInfo);
            echo json_encode($result);
        }
    }

    /**
     * 删除
     */
    function deleteStore()
    {
        $id = input("id");
        $messageRes = $this->model->findstore(['id' => $id]);
        if ($messageRes['errorCode'] == 0) {
            if ($messageRes['data']['user_id']) {
                echo json_encode(Common::errorArray(1, '已绑定用户，不能删除', false));
                die();
            }
            $result = $this->model->deletestore($id);
            echo json_encode($result);
            die();
        }
        echo json_encode(Common::errorArray(1, '不存在', false));
        die();
    }

    /**
     * Info: 上传照片
     * Date: 2022/11/15 11:47
     */
    function uploadPhoto ()
    {
        $model = new LibStore();
        $result = $model->uploadStorePhoto();
        $arr['code'] = 0;
        $arr['msg'] = '上传成功';
        $arr['data'] = [
            'src' => $result['data']['path']
        ];
        echo json_encode($arr);die();
    }

    /**
     * 分页查询
     */
    function pagingStore()
    {
        $args = $this->getArgsList($this, ['memberUsername','username','title','state']);
        $page = $this->getPageInfo();
        $where = [];
        if (!empty($args['memberUsername'])) $where[] = "`memberUsername` like '%" . $args['memberUsername'] . "%'";
        if (!empty($args['username'])) $where[] = "`username` like '%" . $args['username'] . "%'";
        if (!empty($args['title'])) $where[] = "`title` like '%" . $args['title'] . "%'";
        if (!empty($args['address'])) $where[] = "`address` like '%" . $args['address'] . "%'";
        if (($args['state'] == 0 || $args['state'] == 1) && $args['state']!= '') $where[] = "`a`.`state` = '" . $args['state'] . "'";
        $result = $this->model->pagingStore($page, implode(' AND ', $where));
        $userModel = new LibUser();
        $memberModel = new LibMember();
        foreach ($result['data']['dataList'] as &$item)
        {
            $item['parent_nick_name'] = '';
            if ($item['user_id'])
            {
                $findUserRes = $userModel->findUser(['id' => $item['user_id']]);
                if ($findUserRes['errorCode'] == 0)
                {
                    $findMemberRes = $memberModel->findMember(['user_id' => $item['user_id']]);
                    if ($findMemberRes['errorCode'] == 0) {
                        $item['parent_nick_name'] = $findMemberRes['data']['username'];
                    } else {
                        $item['parent_nick_name'] = $findUserRes['data']['nick_name'];
                    }
                }
            }
        }
        echo json_encode($result);
    }

    /**
     * 分页查询
     */
    function pagingStoreList()
    {
        $args = $this->getArgsList($this, ['username','order_id']);
        $page = $this->getPageInfo();
        $where = [];
        $where[] = "`state` = 0";
        $where[] = "`user_id` IS NOT NULL";
        if (!empty($args['username'])) $where[] = "`memberUsername` like '%" . $args['username'] . "%'";
        $orderModel = new LibOrder();
        $findOrderRes = $orderModel->findOrder(['id' => (int)$args['order_id']]);
        $userModel = new LibMember();
        $findUserRes = $userModel->findMember(['user_id' => $findOrderRes['data']['user_id']]);
        $lat = $findUserRes['data']['lat'] ?: '31.82057';
        $lng = $findUserRes['data']['lng'] ?: '117.22901';
        $result = $this->model->pagingStoreList($page, implode(' AND ', $where),$lat,$lng);
        foreach ($result['data']['dataList'] as &$item) {
            $item['distance'] = $item['distance']/1000;
            $item['distance'] = sprintf('%.2f',$item['distance']);
        }
        echo json_encode($result);
    }

    /**
     * Info: 门店状态
     * Date: 2022/6/20 11:24
     */
    function disabledStatus()
    {
        $id = input("id");
        $status = input("state");

        $result = $this->model->findStore(['id' => $id]);
        if ($result['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1, '不存在', ''));
            die();
        }

        $result = $this->model->updateStore(['id' => $id], ['state' => $status]);
        echo json_encode($result);
        die();
    }

    /**
     * Info: 绑定门店
     * Date: 2022/11/15 12:00
     */
    function bindStore ()
    {
        $this->getSetMenu($this);
        return $this->fetch("Store/bindStore/bindStore");
    }

    /**
     * Info: 重置密码
     * Date: 2022/11/17 10:24
     */
    function changePassword ()
    {
        $id = input("id");
        $pass = input("pass");
        $result = $this->model->findStore(['id' => $id]);
        if ($result['errorCode'] == 1) {
            echo json_encode(Common::errorArray(1, '不存在', ''));
            die();
        }
        $this->model->updateStore(['id' => $id], ['password' => trim($pass)]);
        echo json_encode(Common::errorArray(0,'密码已重置，新密码：'.$pass,true));
        die();
    }
}

?>